<template>
  <div class="app-container">
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="160px"
      :label-position="isPhone ? 'top' : 'left'"
    >
      <el-row :gutter="20" v-if="info">
        <el-col :span="12">
          <el-form-item label="学生" label-width="50px">
            <el-select
              v-model="info.userId"
              placeholder="请选择学生"
              clearable
              :disabled="isViewMode || isApproveMode"
            >
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <template v-if="formUserInfo">
          <el-col :span="12">
            <el-form-item label="学校" label-width="50px">
              <el-input
                :value="getUniversityText(formUserInfo.trainUniversity)"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" label-width="50px">
              <el-input v-model="formUserInfo.trainMajor" disabled> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培养单位" label-width="80px">
              <el-input v-model="formUserInfo.trainDeptName" disabled>
              </el-input>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="24">
          <h1>{{ info.planName }}</h1>
        </el-col>
        <el-col :span="12">
          <el-form-item label="填报时间" prop="reportTime">
            <el-date-picker
              v-model="form.reportTime"
              type="date"
              placeholder="请选择填报时间"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              :disabled="isViewMode || isApproveMode"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="月度课题进展描述" prop="monthlyProgress">
            <el-input
              v-model="form.monthlyProgress"
              type="textarea"
              placeholder="请输入月度课题进展描述"
              :rows="3"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="月度学习情况描述" prop="monthlyStudy">
            <el-input
              v-model="form.monthlyStudy"
              type="textarea"
              placeholder="请输入月度学习情况描述"
              :rows="3"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="思想状态" prop="mentalState">
            <el-input
              v-model="form.mentalState"
              type="textarea"
              placeholder="请输入思想状态"
              :rows="3"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="月度企业导师交流次数"
            prop="enterpriseMentorCount"
          >
            <el-input-number
              v-model="form.enterpriseMentorCount"
              :min="0"
              placeholder="请输入交流次数"
              style="width: 100%"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="月度高校导师交流次数" prop="schoolMentorCount">
            <el-input-number
              v-model="form.schoolMentorCount"
              :min="0"
              placeholder="请输入交流次数"
              style="width: 100%"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="企业导师建议" prop="enterpriseMentorAdvice">
            <el-input
              v-model="form.enterpriseMentorAdvice"
              type="textarea"
              placeholder="请输入企业导师建议"
              :rows="3"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="高校导师建议" prop="schoolMentorAdvice">
            <el-input
              v-model="form.schoolMentorAdvice"
              type="textarea"
              placeholder="请输入高校导师建议"
              :rows="3"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="整体进展情况" prop="overallProgress">
            <el-select
              v-model="form.overallProgress"
              placeholder="请选择整体进展情况"
              clearable
              style="width: 100%"
              :disabled="isViewMode"
            >
              <el-option
                v-for="dict in overall_progress"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="是否有其他需解决问题/报告事项"
            prop="hasOtherIssues"
          >
            <el-radio-group
              v-model="form.hasOtherIssues"
              :disabled="isViewMode"
            >
              <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.hasOtherIssues === 'Y'">
          <el-form-item
            label="其他需解决问题/报告事项内容"
            prop="otherIssuesContent"
          >
            <el-input
              v-model="form.otherIssuesContent"
              type="textarea"
              placeholder="请输入其他需解决问题/报告事项内容"
              :rows="3"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.hasOtherIssues === 'Y'">
          <el-form-item
            label="其他需解决问题/报告事项状态"
            prop="otherIssuesStatus"
          >
            <el-select
              v-model="form.otherIssuesStatus"
              placeholder="请选择问题状态"
              clearable
              style="width: 100%"
              :disabled="isViewMode"
            >
              <el-option
                v-for="dict in resolved_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关心关爱活动开展次数" prop="careActivityCount">
            <el-input-number
              v-model="form.careActivityCount"
              :min="0"
              placeholder="请输入活动次数"
              style="width: 100%"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="培训开展次数" prop="trainingCount">
            <el-input-number
              v-model="form.trainingCount"
              :min="0"
              placeholder="请输入培训次数"
              style="width: 100%"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="关心关爱活动内容" prop="careActivityContent">
            <el-input
              v-model="form.careActivityContent"
              type="textarea"
              placeholder="请输入关心关爱活动内容"
              :rows="3"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="培训课程名称" prop="trainingCourseName">
            <el-input
              v-model="form.trainingCourseName"
              placeholder="请输入培训课程名称"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="新增获奖数量" prop="newAwardCount">
            <el-input-number
              v-model="form.newAwardCount"
              :min="0"
              placeholder="请输入获奖数量"
              style="width: 100%"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.newAwardCount > 0">
          <el-form-item label="获奖时间" prop="awardTime">
            <el-date-picker
              v-model="form.awardTime"
              type="date"
              placeholder="请选择获奖时间"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              :disabled="isViewMode"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.newAwardCount > 0">
          <el-form-item label="奖项名称" prop="awardName">
            <el-input
              v-model="form.awardName"
              placeholder="请输入奖项名称"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="新增获批专利数量" prop="newPatentCount">
            <el-input-number
              v-model="form.newPatentCount"
              :min="0"
              placeholder="请输入专利数量"
              style="width: 100%"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.newPatentCount > 0">
          <el-form-item label="获批时间" prop="patentApprovalTime">
            <el-date-picker
              v-model="form.patentApprovalTime"
              type="date"
              placeholder="请选择获批时间"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              :disabled="isViewMode"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.newPatentCount > 0">
          <el-form-item label="专利名称" prop="patentName">
            <el-input
              v-model="form.patentName"
              placeholder="请输入专利名称"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="新完成论文数量" prop="newPaperCount">
            <el-input-number
              v-model="form.newPaperCount"
              :min="0"
              placeholder="请输入论文数量"
              style="width: 100%"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.newPaperCount > 0">
          <el-form-item label="完成时间" prop="paperCompletionTime">
            <el-date-picker
              v-model="form.paperCompletionTime"
              type="date"
              placeholder="请选择完成时间"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              :disabled="isViewMode"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.newPaperCount > 0">
          <el-form-item label="论文名称" prop="paperName">
            <el-input
              v-model="form.paperName"
              placeholder="请输入论文名称"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注信息（选填）"
              :rows="3"
              :disabled="isViewMode"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.approvalStatus === 'rejected'">
          <el-form-item label="审核意见" prop="approvalRemark">
            <el-input
              v-model="form.approvalRemark"
              disabled
              type="textarea"
              placeholder="请输入审核意见"
              :rows="3"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="isApproveMode">
          <el-form-item label="审核意见" prop="approvalRemark">
            <el-input
              v-model="form.approvalRemark"
              type="textarea"
              placeholder="请输入审核意见"
              :rows="3"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 审批进度组件 -->
    <div v-if="form.approvalInfoId" style="margin-bottom: 20px">
      <approval-progress :approval-info-id="form.approvalInfoId" />
    </div>

    <el-row :gutter="10" style="margin-top: 20px">
      <el-col :span="24">
        <template v-if="!isViewMode && !isApproveMode">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button type="primary" @click="saveAndSubmit"
            >保存并提交</el-button
          >
          <el-button @click="goBack">返 回</el-button>
        </template>

        <template v-else-if="isViewMode">
          <el-button @click="goBack">关 闭</el-button>
        </template>

        <template v-else-if="isApproveMode">
          <el-button type="success" @click="handleApprovePass">通 过</el-button>
          <el-button type="danger" @click="handleApproveReject"
            >驳 回</el-button
          >
          <el-button @click="goBack">取 消</el-button>
        </template>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="EnterprisePracticeProgressEdit">
import {
  getDetail,
  editItem,
  addItem,
  getCurrentPlan,
} from "@/api/enterprise-practice-progress";
import { submitApproval, handleApproval } from "@/api/approval";
import { getStudentList } from "@/api/common";
import { useRouter, useRoute } from "vue-router";
import moment from "moment";
import { isPhone } from "@/utils/index";
import ApprovalProgress from "@/components/ApprovalProgress";

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const { sys_yes_no, university, overall_progress, resolved_status } =
  proxy.useDict(
    "sys_yes_no",
    "university",
    "overall_progress",
    "resolved_status"
  );

const formRef = ref();
const info = ref(null);
const form = reactive({
  userId: undefined,
  progressDetails: [],
  approvalRemark: "",
});
const userList = ref([]);

// 判断当前模式
const mode = computed(() => route.query.mode || "edit");
const isViewMode = computed(() => mode.value === "view");
const isApproveMode = computed(() => mode.value === "approve");

const formUserInfo = computed(() =>
  userList.value.find((t) => t.userId === info.value.userId)
);

// 表单验证规则
const rules = {
  userId: [{ required: true, message: "请选择学生", trigger: "change" }],
  reportTime: [
    { required: true, message: "请选择填报时间", trigger: "change" },
  ],
  monthlyProgress: [
    { required: true, message: "请输入月度课题进展描述", trigger: "blur" },
  ],
  monthlyStudy: [
    { required: true, message: "请输入月度学习情况描述", trigger: "blur" },
  ],
  mentalState: [{ required: true, message: "请输入思想状态", trigger: "blur" }],
  enterpriseMentorCount: [
    {
      required: true,
      message: "请输入月度企业导师交流次数",
      trigger: "blur",
    },
  ],
  enterpriseMentorAdvice: [
    { required: true, message: "请输入企业导师建议", trigger: "blur" },
  ],
  schoolMentorCount: [
    {
      required: true,
      message: "请输入月度高校导师交流次数",
      trigger: "blur",
    },
  ],
  schoolMentorAdvice: [
    { required: true, message: "请输入高校导师建议", trigger: "blur" },
  ],
  overallProgress: [
    { required: true, message: "请选择整体进展情况", trigger: "change" },
  ],
  hasOtherIssues: [
    {
      required: true,
      message: "请选择是否有其他需解决问题/报告事项",
      trigger: "change",
    },
  ],
  otherIssuesContent: [
    {
      required: function () {
        return form.hasOtherIssues === "Y";
      },
      message: "请输入其他需解决问题/报告事项内容",
      trigger: "blur",
    },
  ],
  otherIssuesStatus: [
    {
      required: function () {
        return form.hasOtherIssues === "Y";
      },
      message: "请选择其他需解决问题/报告事项状态",
      trigger: "change",
    },
  ],
  careActivityCount: [
    {
      required: true,
      message: "请输入关心关爱活动开展次数",
      trigger: "blur",
    },
  ],
  careActivityContent: [
    { required: true, message: "请输入关心关爱活动内容", trigger: "blur" },
  ],
  trainingCount: [
    { required: true, message: "请输入培训开展次数", trigger: "blur" },
  ],
  trainingCourseName: [
    { required: true, message: "请输入培训课程名称", trigger: "blur" },
  ],
  newAwardCount: [
    { required: true, message: "请输入新增获奖数量", trigger: "blur" },
  ],
  awardTime: [{ required: true, message: "请选择获奖时间", trigger: "change" }],
  awardName: [{ required: true, message: "请输入奖项名称", trigger: "blur" }],
  newPatentCount: [
    { required: true, message: "请输入新增获批专利数量", trigger: "blur" },
  ],
  patentApprovalTime: [
    { required: true, message: "请选择获批时间", trigger: "change" },
  ],
  patentName: [{ required: true, message: "请输入专利名称", trigger: "blur" }],
  newPaperCount: [
    { required: true, message: "请输入新完成论文数量", trigger: "blur" },
  ],
  paperCompletionTime: [
    { required: true, message: "请选择完成时间", trigger: "change" },
  ],
  paperName: [{ required: true, message: "请输入论文名称", trigger: "blur" }],
};

// 高校名称文本显示函数
const getUniversityText = (universityValue) => {
  if (!universityValue) return "未知";
  const dict = university.value?.find((item) => item.value === universityValue);
  return dict ? dict.label : universityValue;
};

// 返回列表
const goBack = () => {
  router.back();
};

// 提交表单
const submitForm = () => {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      const params = {
        ...info.value,
      };
      params.progressDetails = [
        {
          ...form,
          planDetailId: info.value.planDetailId,
          planId: info.value.planId,
        },
      ];
      editItem(params).then((response) => {
        proxy.$modal.msgSuccess("修改成功");
        goBack();
      });
    }
  });
};

// 保存并提交
const saveAndSubmit = () => {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      const params = {
        ...info.value,
      };
      params.progressDetails = [
        {
          ...form,
          planId: info.value.planId,
        },
      ];
      editItem(params).then((response) => {
        proxy.$modal.msgSuccess("修改成功");
        submitApproval({
          businessId: info.value.id,
          approvalTypeCode: "ent_progress_flow",
          approvalInfo: JSON.stringify(info.value)
        }).then(() => {
          proxy.$modal.msgSuccess("提交成功");
          goBack();
        });
      });
    }
  });
};

// 通过审批
const handleApprovePass = () => {
  const approvalData = {
    approvalInfoId: form.approvalInfoId,
    approvalNodeId: form.approvalNodeId,
    approvalStatus: "approved",
    remark: form.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("审批通过");
    goBack();
  });
};

// 驳回审批
const handleApproveReject = () => {
  if (!form.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  const approvalData = {
    approvalInfoId: form.approvalInfoId,
    approvalNodeId: form.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("已驳回");
    goBack();
  });
};

// 初始化数据
onMounted(() => {
  // 获取学生列表
  getStudentList({ roleKey: "student" }).then((res) => {
    userList.value = res.data;
  });

  // 获取详情数据
  const id = route.params.id;
  if (id) {
    getDetail(id).then((response) => {
      console.log(response.data);
      info.value = response.data;
      Object.assign(form, {
        ...response.data.progressDetails?.[0],
        approvalRemark: response.data.approvalRemark || "",
      });
    });
  }
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
